//
//  XJTabBar.m
//  AppFrame
//
//  Created by GXJ on 2017/2/24.
//  Copyright © 2017年 GXJ. All rights reserved.
//

#import "XJTabBar.h"

#import "XJButton.h"

@interface XJTabBar()

@property (nonatomic, weak)UIButton *selectedButton;

@end

@implementation XJTabBar

- (instancetype)init
{
    self = [super init];
    if (self) {
        
       
    }
    return self;
}

- (void)addTabBarItemWithItem:(UITabBarItem *)item
{
    XJButton *button = [[XJButton alloc] initWithFrame:CGRectZero andIsTabItem:YES];
    [self addSubview:button];
    button.item = item;
    [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
}

- (void)buttonPressed:(UIButton *)sender
{
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectButtonFrom:to:)]) {
        [self.delegate tabBar:self didSelectButtonFrom:self.selectedButton.tag to:sender.tag];
    }
    
    self.selectedButton.selected = NO;
    sender.selected = YES;
    self.selectedButton = sender;
    
}



- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat buttonY = 0;
    CGFloat buttonW = self.frame.size.width / self.subviews.count;
    CGFloat buttonH = self.frame.size.height;
    
    for (NSInteger index = 0; index < self.subviews.count; index ++) {
        XJButton *button = self.subviews[index];
        
        CGFloat buttonX = index * buttonW;
        
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        
        button.tag = index;
        
        if (index == 0) {
            
            [self buttonPressed:button];
        }
    }
}

@end
